package com.sq.universe.base.aspect;


import com.alibaba.fastjson.JSON;
import com.sq.universe.base.constants.BaseConstants;
import com.sq.universe.base.constants.LogConstants;
import com.sq.universe.base.dao.LogDao;
import com.sq.universe.base.entity.LogEntity;
import com.sq.universe.system.entity.UserEntity;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.web.util.WebUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.crazycake.shiro.RedisSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Configuration
public class LogAspect {

    private static Map<String,Integer> tableExists = new HashMap<String,Integer>();

    @Autowired
    private LogDao logDao;

    @Autowired
    private RedisSessionDAO redisSessionDAO;

    /**
     * 本地异常日志记录对象
     */
    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * Controller层切点
     */
    @Pointcut("execution(public * com.sq.universe.*.controller.*.*(..)))")
    public void controllerAspect() {

    }

    /**
     * Service层切点
     */
    @Pointcut("execution(public * com.sq.universe.*.service.impl.*.*(..)))")
    public void serviceAspect() {

    }

    /**
     * 异常通知 用于拦截service层记录异常日志
     *
     * @param joinPoint
     * @param ex
     */
    @AfterThrowing(pointcut = "serviceAspect()", throwing = "ex")
    public void doAfterThrowing(JoinPoint joinPoint, Throwable ex) {
        try {
            insertLog(joinPoint,LogConstants.SERVICE);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }



        /**
         * controller 层日志入库
         * @param joinPoint
         */
    @Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint) {
        try {
            insertLog(joinPoint,LogConstants.CONTROLLER);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 通过request获取请求的IP
     * @param request
     * @return
     */
    public  static  String  getIpAddress(HttpServletRequest  request)  {
        String  ip  =  request.getHeader("x-forwarded-for");
        if (ip  ==  null  ||  ip.length()  ==  0  ||  "unknown".equalsIgnoreCase(ip))  {
            ip  =  request.getHeader("Proxy-Client-IP");
        }
        if (ip  ==  null  ||  ip.length()  ==  0  ||  "unknown".equalsIgnoreCase(ip))  {
            ip  =  request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip  ==  null  ||  ip.length()  ==  0  ||  "unknown".equalsIgnoreCase(ip))  {
            ip  =  request.getRemoteAddr();
        }
        if (ip.contains(","))  {
            return  ip.split(",")[0];
        }
        else  {
            return  ip;
        }
    }


    /**
     * 获取当前年月
     * @return
     */
    public String getCurrentMonth(){
        SimpleDateFormat simpleDateFormate = new SimpleDateFormat("yyyyMM");
        return simpleDateFormate.format(new Date());
    }

    /**
     * 判断表是否存在，若不存在则创建表
     * @param tableName
     */
    public void createTableIfNEX(String tableName){
        if(tableExists.get(tableName) != null){
            return ;
        }else{
            Integer size = logDao.existTable(tableName);
            if(size == null || size == 0){
                logDao.createTable(tableName);
            }
            tableExists.clear();
            tableExists.put(tableName,1);
        }
    }

    /**
     * 插入日志注解
     * @param joinPoint
     * @param type
     * @throws Exception
     */
    public void insertLog(JoinPoint joinPoint,String type) throws Exception {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String id = WebUtils.toHttp(request).getHeader("X-Token");
        //类名
        String className = joinPoint.getTarget().getClass().getName();
        //请求方法
        String method = joinPoint.getSignature().getName() + "()";
        //方法参数
        String methodParam = JSON.toJSONString(joinPoint.getArgs());
        //获取IP
        String IP = getIpAddress(request);
        //获取描述
        String description = LogConstants.CONTROLLER;
        if(type.equals(LogConstants.SERVICE)){
            description = LogConstants.SERVICE;
        }
        String currentMonth = this.getCurrentMonth();
        String tableName = "system_log_" + currentMonth;
        createTableIfNEX(tableName);
        LogEntity logEntity = new LogEntity();
        logEntity.setLogCreateTime(new Date());
        logEntity.setLogIp(IP);
        logEntity.setLogClassName(className);
        logEntity.setLogMethod(method);
        logEntity.setLogParams(methodParam);
        logEntity.setLogDescription(description);
        logEntity.setMonth(currentMonth);
        logEntity.setLogType(type);
        if( id != null){
            SimpleSession simpleSession = (SimpleSession) redisSessionDAO.readSession(id);
            UserEntity userEntity = (UserEntity) simpleSession.getAttribute(BaseConstants.CURRENT_USER);
            logEntity.setLogCreateUser(userEntity.getUserLoginName());
            logEntity.setLogCreateTime(new Date());
        }
        logDao.insert(logEntity);
    }

}
